// JavaScript Document


function ChatMsg(){}

ChatMsg.prototype={
	//配置聊天信息的颜色
	chatMessageColor : {
		joinRoom  : "#00bbf2", //进入房间
		fansName  : "#3c9cfe", //粉丝姓名
		chatMsg   : "#333333", //聊天信息
		fansGift  : "#ff6147", //粉丝礼物
		//anchorBg  : "#00bbf2", //主播图标背景
		//anchorMsg : "#f69200", //主播信息
		//manageBg  : "#00bbf2", //管理员图标背景
		//manageMsg : "#f69200"  //管理员信息
	},
	init : function(token,userId,roomId,containerDivId)
	{
		// token
		// userId   用户ID
		// roomId   房间ID
		// oChatBox 聊天消息容器
		
		//拉取聊天信息条数
		var chatListCount = 10; 
		
		var containerDiv = $("#"+containerDivId);
		
		//初始化SDK，传入App Key
		//App Key自己申请
		//本地存储方式初始化
		RongIMLib.RongIMClient.init("8brlm7ufra1l3");
		
		// 设置连接监听状态 （ status 标识当前连接状态）
		// 连接状态监听器
		RongIMClient.setConnectionStatusListener({
			onChanged: function (status)
			{
				switch (status)
				{
					//链接成功
					case RongIMLib.ConnectionStatus.CONNECTED:
						containerDiv.append("<span class='chatMsgList'>弹幕连接成功</span>");
						break;
					//正在链接
					case RongIMLib.ConnectionStatus.CONNECTING:
						containerDiv.append("<span class='chatMsgList'>弹幕连接中...</span>");
						break;
					//重新链接
					case RongIMLib.ConnectionStatus.DISCONNECTED:
						containerDiv.append("<span class='chatMsgList'>弹幕已断开...</span>");
						break;
					//其他设备登录
					case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
						console.log('其他设备登录');
						break;
					//网络不可用
					case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
						console.log('网络不可用');
					    break;
				}
			}
		});
		
		// 消息监听器
		RongIMClient.setOnReceiveMessageListener({
			// 接收到的消息
			onReceived: function (message)
			{
				// 判断消息类型
				switch(message.messageType)
				{
					case RongIMClient.MessageType.TextMessage:
						// 发送的消息内容将会被打印
						break;
					case RongIMClient.MessageType.VoiceMessage:
						// 对声音进行预加载                
						// message.content.content 格式为 AMR 格式的 base64 码
						RongIMLib.RongIMVoice.preLoaded(message.content.content);
						break;
					case RongIMClient.MessageType.UnknownMessage:
					console.log(message);
						if (typeof(message.content.user) == 'undefined')
						{
                            if (typeof(message.content.extra) != 'undefined')
							{
                                var joinRoom = message.content.extra;
                                var obj = $.parseJSON(joinRoom);
                                if (typeof(message.content.item_id) != 'undefined')
								{
                                    var item_id = message.content.item_id;
                                    if ((item_id == 200) || (item_id == 201) || (item_id == 202))
									{
                                        //消息
                                        if (typeof (obj.textColor) != 'undefined'||typeof (obj.action) != 'undefined')
										{

                                            containerDiv.append("<span class='span_block' style='color:" + this.chatMessageColor.fansName + "'>" + message.content.content + "</span>");
                                        }
										else
										{ 
                                            containerDiv.append("<span class='span_block'>" + message.content.content.replace("%s", obj.action.name) + "</span>");
                                        }
                                    }
									else
									{
                                        //送礼物
                                        if (typeof (obj.textColor) != 'undefined')
										{
                                            containerDiv.append("<span class='span_block' style='color:" + this.chatMessageColor.fansGift + "'>" + message.content.content + "</span>");
                                        }
                                    }
                                }
                            }
							document.getElementById(containerDivId).scrollTop += 30;
                        }
                        else
						{
                            if (typeof(message.content.extra) == 'undefined')
							{
                                var userId = message["content"]["user"]["id"];
                                var userLevel = message["content"]["level"];
                                var leftContent = "<span class='span_block'>";
                                var rightContent = "<span style='color:" + this.chatMessageColor.fansName + "'>" + message.content.user.name + ":&nbsp;</span>" +
                                    "<span style='color:" + this.chatMessageColor.chatMsg + "'>" + message.content.content + "</span></span>";
                                _this.htmlLevel(userId,
                                    userLevel,
                                    containerDiv,
                                    leftContent,
                                    rightContent
                                )
                            }
                            else {

                                var msgStr = message.content.extra;
                                var extraObj = $.parseJSON(msgStr);
                                if (typeof(message.content.item_id) != 'undefined') {
                                    var item_id = message.content.item_id;
                                    if ((item_id == 200) || (item_id == 201) || (item_id == 202))
									{
                                        if (typeof(extraObj.textColor) != 'undefined')
										{
                                            containerDiv.append("<span class='span_block' style='color:" + this.chatMessageColor.fansName + "'>" + message.content.content + "</span>");
                                        }
                                    }
                                    else
									{
                                        if (typeof(extraObj.textColor) != 'undefined')
										{
                                            if (typeof (extraObj.superId) != 'undefined')
											{
                                                if (typeof(extraObj.nickColor) != 'undefined')
												{
                                                    var userId = message["content"]["user"]["id"];
                                                    var userLevel = message["content"]["level"];
                                                    var leftContent = "<span class='span_block'>";
                                                    var rightContent = "<span style='color:" + this.chatMessageColor.fansName + "'>" + message.content.user.name + ":</span><span style='color:" + this.chatMessageColor.chatMsg + "'>" + message.content.content + "</span></span>";
                                                    _this.htmlLevel(userId, userLevel,
                                                        containerDiv,
                                                        leftContent,
                                                        rightContent
                                                    )
                                                    containerDiv.append("<span class='span_block' ><span style='color:" + extraObj.nickColor + "; '>" + message.content.user.name + ":</span><span style='color:" + this.chatMessageColor.chatMsg + "'>" + message.content.content + "</span></span>");
                                                }
												else
												{
                                                    var userId = message["content"]["user"]["id"];
                                                    var userLevel = message["content"]["level"];
                                                    var leftContent = "<span class='span_block'>";
                                                    var rightContent = "<span style='color:" + this.chatMessageColor.fansName + "'>" + message.content.user.name + ":</span><span style='color:" + this.chatMessageColor.chatMsg + "'>" + message.content.content + "</span></span>";
                                                    _this.htmlLevel(userId,
                                                        userLevel,
                                                        containerDiv,
                                                        leftContent,
                                                        rightContent
                                                    )

                                                }
                                            }
                                            else 
											{
                                                var userId = message["content"]["user"]["id"];
                                                var userLevel = message["content"]["level"];
                                                var leftContent = "<span class='span_block'>";
                                                var rightContent = "<span style='color:" + this.chatMessageColor.fansName + "'>" + message.content.user.name + ":</span><span style='color:" + this.chatMessageColor.chatMsg + "'>" + message.content.content + "</span></span>";
                                                _this.htmlLevel(userId,
                                                    userLevel,
                                                    containerDiv,
                                                    leftContent,
                                                    rightContent
                                                )
											}
                                        }
                                        else
										{
                                            var userId = message["content"]["user"]["id"];
                                            var userLevel = message["content"]["level"];
                                            var leftContent = "<span class='span_block'>";
                                            var rightContent = "<span style='color:" + this.chatMessageColor.fansName + "'>" + message.content.user.name + ":</span><span style='color:" + this.chatMessageColor.chatMsg + "'>" + message.content.content + "</span></span>";
                                            _this.htmlLevel(userId,
                                                userLevel,
                                                containerDiv,
                                                leftContent,
                                                rightContent
                                            )
                                        }
                                        document.getElementById(containerDivId).scrollTop += 30;
                                    }
                                }
                            }
                            document.getElementById(containerDivId).scrollTop += document.getElementById(containerDivId).scrollHeight;
                        }
						break;
				}
			}
		});
		
		// 连接融云服务器。
		RongIMClient.connect(token, {
			onSuccess: function(userId)
			{
				//从服务器拉取聊天信息，并加入聊天室
				RongIMClient.getInstance().joinChatRoom(roomId, chatListCount,{
					//成功加入聊天室
					onSuccess: function()
					{
						containerDiv.append("<span class='chatMsgList'>聊天室连接成功</span>");
					},
					//加入聊天室失败
					onError: function(error)
					{
						containerDiv.append("<span class='chatMsgList'>聊天室连接失败</span>");
					}
				});
			},
			onTokenIncorrect: function()
			{
				console.log('token无效');
			},
			onError:function(errorCode)
			{
				var info = '';
				switch (errorCode)
				{
					case RongIMLib.ErrorCode.TIMEOUT:
					info = '超时';
					break;
				case RongIMLib.ErrorCode.UNKNOWN_ERROR:
					info = '未知错误';
					break;
				case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
					info = '不可接受的协议版本';
					break;
				case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
					info = 'appkey不正确';
				    break;
				case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
				  	info = '服务器不可用';
				  	break;
			  }
			 console.log("聊天室错误：" + errorCode);
			}
		});
	},
	sendMsg:function()
	{
		var msg = new RongIMLib.TextMessage({content:"hello",extra:"附加信息"});
		//或者使用RongIMLib.TextMessage.obtain 方法.具体使用请参见文档
		//var msg = RongIMLib.TextMessage.obtain("hello");
		var conversationtype = RongIMLib.ConversationType.PRIVATE; // 私聊
		var targetId = "xxx"; // 目标 Id
		RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg,{
			// 发送消息成功
			onSuccess: function (message)
			{
				//message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
				console.log("Send successfully");
			},
			onError: function (errorCode,message)
			{
				var info = '';
				switch (errorCode)
				{
					case RongIMLib.ErrorCode.TIMEOUT:
						info = '超时';
						break;
					case RongIMLib.ErrorCode.UNKNOWN_ERROR:
						info = '未知错误';
						break;
					case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
						info = '在黑名单中，无法向对方发送消息';
						break;
					case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
						info = '不在讨论组中';
						break;
					case RongIMLib.ErrorCode.NOT_IN_GROUP:
						info = '不在群组中';
						break;
					case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
						info = '不在聊天室中';
						break;
					default :
						info = x;
						break;
				}
				console.log('发送失败:' + info);
			}
		});	
	}
}


